package com.wuhan.template.module.wode.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.wuhan.template.R;
import com.wuhan.template.base.BaseActivity;
import com.wuhan.template.base.BaseApplication;
import com.wuhan.template.constant.Urls;
import com.wuhan.template.module.wode.entity.TodayImageEntity;
import com.wuhan.template.utils.EventMessage;
import com.wuhan.template.utils.OkHttpUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import butterknife.BindView;

/**
 * Created by Administrator on 2016/5/14 0014.
 */
public class TodayImageActivity extends BaseActivity{


    @BindView(R.id.today_image)
    protected ImageView imageView;

    @BindView(R.id.image_down)
    protected ImageView down;

    private DisplayImageOptions options;
    private ImageLoader loader;
    private String imageUrl;
    private Bitmap bitmap;

    private File myCaptureFile;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_today_image;
    }

    @Override
    protected void initViews() {

        options = new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .build();
        loader = ((BaseApplication)(getApplicationContext())).getImageLoader();

        down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            URL url = new URL(imageUrl);
                            HttpURLConnection con  = (HttpURLConnection) url.openConnection();
                            if (con.getResponseCode()==200){
                                InputStream inputStream = con.getInputStream();
                                bitmap = BitmapFactory.decodeStream(inputStream);
                                new Thread(saveFileRunnable).start();
                            }
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });


    }

    private String mSaveMessage;

    private String imageName = ""+Math.random()*10000;
    private Runnable saveFileRunnable = new Runnable(){
        @Override
        public void run() {
            try {
                saveFile(bitmap,imageName+".jpg");
                mSaveMessage = "图片保存成功！";
            } catch (IOException e) {
                mSaveMessage = "图片保存失败！";
                e.printStackTrace();
            }
            messageHandler.sendMessage(messageHandler.obtainMessage());
        }

    };

    private Handler messageHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
           /* if(myCaptureFile.exists())
            {
                Toast.makeText(TodayImageActivity.this, "已经下载了", Toast.LENGTH_SHORT).show();
            }*/
            Toast.makeText(TodayImageActivity.this, mSaveMessage, Toast.LENGTH_SHORT).show();
        }
    };

    private String ALBUM_PATH= Environment.getExternalStorageDirectory() + "/download_test/";

    public void saveFile(Bitmap bm, String fileName) throws IOException {
        File dirFile = new File(ALBUM_PATH);
        if(!dirFile.exists()){
            dirFile.mkdir();
        }
        myCaptureFile = new File(ALBUM_PATH + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
    }


    @Override
    protected void loadData() {
        OkHttpUtils.get(Urls.MEITU,null);
    }

    @Override
    protected void postEventResult(@NonNull EventMessage message) {
        if(message.type.equals(Urls.MEITU)){
            Gson gson = new Gson();
            TodayImageEntity todayImageEntity = gson.fromJson(message.result, TodayImageEntity.class);
            TodayImageEntity.AdBean.BeforeBean.ImageBean image = todayImageEntity.getAd().getBefore().getImage();
            imageUrl = image.getHost() + image.getDir() + image.getFilepath() + image.getFilename();
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            loader.displayImage(imageUrl,imageView,options);
        }
    }
}
